#!/bin/bash

killall daemon
killall tuntap_bb
sleep 3

DEVICE_ID="1d6b:8030"

if lsusb | grep -q "$DEVICE_ID"; then
    echo "Device $DEVICE_ID detected, initializing 401"

    ln -s /dev/net/tun /dev/tun
    echo "Initializing Linux TUN"
    sleep 1
    ./bin/daemon &
    echo "Starting daemon"
    sleep 5

    echo "Upgrading 401, DEV firmware"
    ./dev_helper/ota -f firmware_14G/VT4_DEV-USBBOX_*.img
    sleep 5
    echo "Restoring factory settings"
    ./bin/bb_test -R
    sleep 3
    echo "Rebooting device"
    ./bin/bb_test -o
    sleep 5
    echo "Setting role to DEV"
    ./bin/bb_test -r 1
    echo "Starting pairing process"
    ./bin/bw_update_demo -s 0 -r -t 100 -d -A -j
    sleep 2

    echo "Pairing successful, creating virtual network interface"

    ./dev_helper/tuntap_bb -p 2 -i 192.168.144.66 -u 0 -d tun -r 5000 -t 40000 &
    sleep 4

    echo "Success, attempting to ping 192.168.144.55"

    TARGET_IP="192.168.144.55"

    if ping -c 1 -W 1 $TARGET_IP &> /dev/null; then
        echo "Success: $TARGET_IP is reachable"
    else
        echo "Failed: $TARGET_IP is unreachable"
    fi

    exit 0
else
    echo "Device $DEVICE_ID not detected, please check if the 401 device is functioning properly"
    exit 1
fi
